package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WechatService wechatService;

    private static List<String> NICK_NAME_PREFIX_LIST = Arrays.asList("钱途无量",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginDto dto) {

        String openId = wechatService.getOpenId(dto.getCode());
        if (openId == null) {
            throw new BaseException("登录失败");
        }
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        if (familyMember==null){
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());
            familyMember = FamilyMember.builder().openId(openId).phone(phoneNum).build();
            //打乱集合中元素顺序，目的是随机获取元素
            Collections.shuffle(NICK_NAME_PREFIX_LIST);
            familyMember.setName(NICK_NAME_PREFIX_LIST.get(0)+ RandomStringUtils.randomNumeric(4));
            this.save(familyMember);
        }

        if (StrUtil.isBlank(familyMember.getPhone())){
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());
            FamilyMember familyMember1 = FamilyMember.builder().id(familyMember.getId()).phone(phoneNum).build();
            this.updateById(familyMember1);
        }
        Map<String,Object> userInfo = Map.of("userId", familyMember.getId(), "nickName", familyMember.getName());
        String token = tokenService.createToken(userInfo);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }
}
